//
//  CSniChengViewController.m
//  ZSYH
//
//  Created by 主事丫环 on 2019/4/11.
//  Copyright © 2019 魏堰青. All rights reserved.
//

#import "CSniChengViewController.h"

@interface CSniChengViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *mytf;

@end

@implementation CSniChengViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        self.title = @"修改昵称";
    
    [self.leftbutton setTitle:@"取消" forState:(UIControlStateNormal)];
    [self.rightbutton setTitle:@"确定" forState:(UIControlStateNormal)];
    
    self.mytf.text = _model.name;
    [self.mytf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.mytf becomeFirstResponder];
    self.mytf.delegate = self;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    
}
- (void)leftClick{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)rightClick{
    if (self.mytf.text.length <1) {
        ShowToastWithText(@"用户名不能为空");
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"name"] = _mytf.text;
    
    [NetWorkTool POST:changeInfo param:param success:^(id dic) {
        ShowToastWithText(@"修改成功");
        [self.navigationController popViewControllerAnimated:YES];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
    
    
}
- (IBAction)actiondfdf:(UIButton *)sender {
    self.mytf.text = @"";
    [self.mytf becomeFirstResponder];
}
- (void)textFieldDidChange:(UITextField *)textField
{
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 5;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        
        if (toBeString.length > maxLength){
            
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
@end
